package org.hdax.dm.rest.service;

import org.hdax.dm.dao.entitydao.DmImageDao;
import org.hdax.dm.entity.image.DmImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@RestController
public class RestImageService {
    @Autowired
    private DmImageDao dmImageDao;

    @PostMapping(path = "/findByImage")
    public List<DmImage> findByDmitem(@RequestBody DmImage dmImage) {
        return dmImageDao.findAll(where(dmImage), Sort.by(Sort.Order.asc("sort")));
    }

    public Specification<DmImage> where(DmImage dmImage) {
        return new Specification<DmImage>() {
            @Override
            public Predicate toPredicate(Root<DmImage> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (dmImage != null) {
                    if (dmImage.getCategory() != null && dmImage.getCategory() >= 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("category").as(Integer.class), dmImage.getCategory()));
                    }
                    if (dmImage.getType() != null && dmImage.getType() >= 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("type").as(Integer.class), dmImage.getType()));
                    }
                    if (dmImage.getTargetId() != null && dmImage.getTargetId() > 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("targetId").as(Integer.class), dmImage.getTargetId()));
                    }
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
            }
        };
    }
}
